package com.fjzn.detect.service.security;

import com.fjzn.detect.common.enums.web.ResponseStatus;
import com.fjzn.detect.repository.user.entity.SysUser;
import com.fjzn.detect.service.exection.BusinessException;
import com.fjzn.detect.service.jwt.TokenService;
import com.fjzn.detect.service.user.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 登录校验方法
 *
 * @author helloworld
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private ISysUserService userService;

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {

        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new BusinessException(ResponseStatus.账号密码不匹配);
            } else {
                throw new BusinessException(ResponseStatus.登录失败);
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        String token = tokenService.createToken(loginUser);

        updateLoginInfo(loginUser);

        return token;
    }

    /**
     * 更新用户登录信息
     * @param loginUser
     */
    private void updateLoginInfo(LoginUser loginUser){
        SysUser user = loginUser.getUser();
        user.setLoginDate(LocalDateTime.now());
        user.setLoginIp(loginUser.getIpaddr());
        userService.updateById(user);
    }

}
